﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MxWeiXinPF.Common;
using MxWeiXinPF.BLL;

namespace MxWeiXinPF.Web.admin.wxapp
{
    public partial class addUserWxapp : Web.UI.ManagePage
    {

        wxapp_userList auBll = new wxapp_userList();

        wxapp_appinfo appinfoBll = new wxapp_appinfo();


        protected void Page_Load(object sender, EventArgs e)
        {
            int storeId = MyCommFun.RequestInt("storeId", 0);
            if (!Page.IsPostBack)
            {
                BindStore(storeId);
                BindWxappList(storeId);

            }
          

        }

        #region 赋值操作=================================

        /// <summary>
        /// 绑定门店
        /// </summary>
        /// <param name="storeId">门店id</param>
        public void BindStore(int storeId)
        {
            BLL.manager bll = new BLL.manager();
            DataSet storeDs = bll.GetList(10000000, "is_lock=0", "sort_id asc,id desc");
            this.ddlStore.Items.Clear();
            this.ddlStore.Items.Add(new ListItem("====请选择门店====", ""));
            if (storeDs != null && storeDs.Tables[0] != null && storeDs.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in storeDs.Tables[0].Rows)
                {
                    this.ddlStore.Items.Add(new ListItem(dr["storeName"].ToString() + "_" + dr["user_name"].ToString(), dr["id"].ToString()));
                }
            }
            ddlStore.DataBind();

            if (storeId != 0)
            {
                ddlStore.SelectedValue = storeId.ToString();
            }
           

        }


        private void BindWxappList(int storeId)
        {
            int wxappid = 0;
            this.ddlWxAppList.Items.Clear();

            IList<Model.wxapp_appinfo> appinfolist = new List<Model.wxapp_appinfo>();
            if (storeId != 0)
            {
                //取该门店未购买过的小程序
                appinfolist = appinfoBll.GetModelList("status=1 and id not in (select wxappId from wxapp_userList  where userid =" + storeId + ")");
            }
            else
            {
                appinfolist = appinfoBll.GetModelList("status=1 ");
            }
            if (appinfolist != null && appinfolist.Count > 0)
            {
                this.ddlWxAppList.Items.Add(new ListItem("====请选择小程序====", ""));
                foreach (Model.wxapp_appinfo appinfo in appinfolist)
                {
                    this.ddlWxAppList.Items.Add(new ListItem(appinfo.wxappName, appinfo.id.ToString()));
                }
            }
            else
            {
                this.ddlWxAppList.Items.Add(new ListItem("=暂无可购的小程序=", ""));
            }

            ddlWxAppList.DataBind();

        }


        #endregion



        /// <summary>
        /// 生成二维码的逻辑：生成订单，并且跳转到生成二维码页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //购买
            int storeId =MyCommFun.Str2Int( ddlStore.SelectedItem.Value,0);
            int wxappid = MyCommFun.Str2Int(ddlWxAppList.SelectedItem.Value,0);
            int status = MyCommFun.Str2Int(rblStatus.SelectedItem.Value);
            DateTime validDate = MyCommFun.Obj2DateTime(txtverifyTime.Text.Trim());
            if (storeId == 0 || wxappid == 0)
            {
                //失败，在本页面
                JscriptMsg("请选择正确的店铺和小程序", "back");
                return;
            }


            string msg = "";

            int  auserId = BuyWxapp(storeId, wxappid, status, validDate, out msg);
            if (auserId > 0)
            {
                //购买成功,跳转到生成二维码页面
                //wxappCreateQRPic.aspx?auid=14
                JscriptMsg("购买成功！", "wxappCreateQRPic.aspx?auid="+ auserId);
            }
            else
            {
                //失败，在本页面
                JscriptMsg(msg, "back");
                return;

            }





        }

        /// <summary>
        /// 购买小程序，购买成功返回购买的用户表wxapp_userList主键id,否则0
        /// </summary>
        /// <param name="storeId">门店id,即为管理员表的主键id</param>
        /// <param name="wxappId">小程序表的主键id</param>
        /// <param name="status">审核状态（0申请中，1审核通过，2审核失败）</param>
        /// <param name="msg">返回语</param>
        /// <returns></returns>
        private int BuyWxapp(int storeId, int wxappId, int status, DateTime validDate, out string msg)
        {
            int  ret = 0;
            msg = "";
            Model.wxapp_appinfo appModel = appinfoBll.GetModel(wxappId);
            //判断该小程序是否可以购买
            if (appModel != null && appModel.status != 1)
            {
                msg = "小程序未上线，不能购买";
                return 0;

            }
            BLL.manager managerBll = new BLL.manager();
            //门店用户
            Model.manager storeModel = managerBll.GetModel(storeId);
            if (storeModel == null)
            {
                msg = "不存在该用户";
                return 0;
            }

            Model.wxapp_userList appUser = new Model.wxapp_userList();


            DataTable oldBuyInfo = auBll.GetModelByWxappIdAndUserId(wxappId, storeId);
            if (oldBuyInfo != null && oldBuyInfo.Rows.Count > 0)
            {
                //已购买,并且还未过期，不能再次购买
                msg = "已购买，不能再次购买";
                return 0;
            }

            Model.manager loginManager = GetAdminInfo();

            BLL.wxapp_buyOrders orderBll = new wxapp_buyOrders();
            Model.wxapp_buyOrders order = new Model.wxapp_buyOrders();
            DateTime now = DateTime.Now;


            //如果是第一次购买
            //1 初始化用户的的小程序数据
            appUser.userId = storeId;
            appUser.wxappId = wxappId;
            appUser.applyTime = now;
            appUser.status = status;
            appUser.price = appModel.currPrice;
            appUser.validDate = validDate;
            appUser.verifyPerson = loginManager.user_name;
            appUser.verifyTime = now;

            //2 订单数据
            order.wxappId = wxappId;
            order.userId = storeId;
            order.username = storeModel.user_name;
            order.storeName = storeModel.storeName;
            order.wxappName = appModel.wxappName;
            order.price = appModel.currPrice;
            order.status = 1;
            order.orderNo = Utils.Number(10);
            order.tradeNo = "";
            order.paymentType = "outline";//下线支付
            order.paymentStatus = 1;//支付成功
            order.paymentTime = now;
            order.createTime = now;
            order.createPersonId = loginManager.id;
            order.buyType = 1;
            order.remark = "(管理员)第一次购买小程序" + appModel.wxappName;
            int retappUserId = auBll.Add(appUser);
            if (retappUserId > 0)
            {
                int retOrderId = orderBll.Add(order);

                AddAdminLog(MXEnums.ActionEnum.Invalid.ToString(), "管理员操作：用户(user_id=" + storeId + ")购买了小程序（id=" + wxappId + "OrderId=" + retOrderId + ")"); //记录日志//1e2124dd04e11d01b9df2865f85944be

                return retappUserId;
            }
            else
            {
                msg = "插入数据库失败";
                return 0;
            }



        }

    }
}